package com.binarysoft.cmdhandler.common.job;

import java.util.Collection;
import java.util.StringTokenizer;

import com.binarysoft.service.common.job.JobConfig;
import com.binarysoft.service.common.job.JobService;
import common.framework.command.handler.AbstractCommandHandler;
import common.framework.command.helper.CommandHelper;
import common.framework.command.server.Terminal;
import common.framework.dsb.annotation.DSBCmd;
import common.framework.dsb.client.DefaultServiceFactory;
import common.framework.dsb.client.ServiceFactory;

@DSBCmd("job")
public class JobCmdHandler extends AbstractCommandHandler {

	@Override
	public void handle(String args, Terminal terminal) throws Exception {
		terminal.println("");
		StringTokenizer stier = new StringTokenizer(args);
		int count = stier.countTokens();
		if (count < 2) {
			terminal.println(" Usage:");
			terminal.println(" job ls               -- list all jobs");
			terminal.println(" job fire <name>      -- fire job with given <name>");
			terminal.println("");
			return;
		}
		stier.nextToken();
		String cmd = stier.nextToken();

		if ("ls".equalsIgnoreCase(cmd) && count == 2) {
			listJobs(terminal);
		} else if ("fire".equalsIgnoreCase(cmd) && count == 3) {
			String jobName = stier.nextToken();
			fireJob(terminal, jobName);
		} else {
			terminal.println(" Usage:");
			terminal.println(" job ls               -- list all jobs");
			terminal.println(" job fire <name>      -- fire job with given <name>");
		}
		terminal.println("");
	}

	private void fireJob(Terminal terminal, String jobName) throws Exception {
		ServiceFactory serviceFactory = new DefaultServiceFactory();
		JobService jobService = serviceFactory.lookup("DSB/JobService");
		boolean result = jobService.fireJob(jobName);
		if (result) {
			terminal.println(" Fire job [" + jobName + "] success.");
		} else {
			terminal.println(" Fire job [" + jobName + "] failed.");
		}

	}

	private void listJobs(Terminal terminal) throws Exception {
		ServiceFactory serviceFactory = new DefaultServiceFactory();
		JobService jobService = serviceFactory.lookup("DSB/JobService");
		Collection<JobConfig> configs = jobService.getJobConfigs();
		String[] tableHAD = { "Name", "Group", "Cron_Exp", "Class" };
		String[] tableGAP = { "----", "-----", "--------", "-----" };
		int[] format = { 20, 15, 20, 30 };
		terminal.println(CommandHelper.format(tableHAD, format));
		terminal.println(CommandHelper.format(tableGAP, format));
		for (JobConfig jobConfig : configs) {
			Object[] row = { jobConfig.getName(), jobConfig.getGroup(), jobConfig.getCron_exp(), jobConfig.getJob_class() };
			terminal.println(CommandHelper.format(row, format));
		}
		terminal.println("");
		terminal.println(" Total " + configs.size() + " job(s).");
	}
}